package com.yoipdu.im1.service;

import com.alibaba.fastjson.JSON;
import com.yoipdu.im1.entity.Content;
import com.yoipdu.im1.util.JsonData;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

//WebSocket服务
@Component
@ServerEndpoint("/websocket/{id}")
//此注解相当于设置访问URL
public class WebSocketService {

    private static Map<String, Session> list = new HashMap<String, Session>();
    private JsonData json;

    public int getSize() {
        return list.size();
    }

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String id) {
        list.put(id, session);
    }

    @OnClose
    public void onClose(@PathParam(value = "id") String id) {
        try {
            list.remove(id);
            sendAllMessage(list.size());
        } catch (NullPointerException ignored) {

        }
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:" + message);
    }

    // 此为广播消息
    public void sendAllMessage(Content content) {
        json = new JsonData();
        System.out.println(content.getId() + "广播{" + content.getContent() + "}");
        json.put("content", content);
        json.put("number", list.size());
        for (Session s : list.values()) {
            try {
                s.getAsyncRemote().sendText(JSON.toJSONString(json.to()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为广播消息
    public void sendAllMessage(int number) {
        json = new JsonData();
        json.put("number", number);
        for (Session s : list.values()) {
            try {
                s.getAsyncRemote().sendText(JSON.toJSONString(json.to()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
//    public void sendOneMessage(Integer fromUid, Integer toUid, String message, int itemsId) {
//        WebSocketMessage ws2 = webSockets.get(toUid);
//        try {
//            ws2.putMessage(fromUid, message, itemsId);
//            if (ws2.getSession() != null) {
//                //在线
//                ws2.getSession().getAsyncRemote().sendText(JSONUtil.toJsonStr(ws2.getMessage(fromUid)));
//            }
//        } catch (NullPointerException ignored) {
//            // 忽略
//        }
//    }

}
